package com.xyhuo.leetcode.november;

/**
 * 字符串转换整数（atoi）
 * https://leetcode.cn/problems/string-to-integer-atoi/
 *
 * @time 2023/11/30
 */
public class MyAtoi {

//    public static void main(String[] args) {
//        MyAtoi myAtoi = new MyAtoi();
//        myAtoi.myAtoi("  +  413");
//        System.out.println();
//    }

    public int myAtoi(String s) {
        char[] charArray = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        int len = charArray.length;

        int pre = 1;
        int numLen = 0;
        boolean findPre = false;

        for (int i = 0; i < len; i++) {
            if (charArray[i] == ' ') {
                if (sb.length() == 0 && !findPre) {
                    continue;
                } else {
                    break;
                }
            }

            if (!findPre && (charArray[i] == '+' || charArray[i] == '-') && numLen == 0) {
                findPre = true;
                if (charArray[i] == '-') {
                    pre = -1;
                }
                continue;
            }
            if (charArray[i] <= 57 && charArray[i] >= 48) {
                numLen++;
                sb.append(charArray[i]);
            } else {
                break;
            }
        }
        while (sb.indexOf("0") == 0) {
            sb = sb.deleteCharAt(0);
        }
        if (sb.length() == 0) {
            return 0;
        }
        if (findPre && pre == -1) {
            sb.insert(0, "-");
        }
        String strNum = sb.toString();
        if (pre < 0 && (strNum.length() > 11 || (strNum.length() == 11 && strNum.compareTo("-2147483648") > 0))) {
            return -2147483648;
        }
        if (pre > 0 && (strNum.length() > 10 || (strNum.length() >= 10 && strNum.compareTo("2147483647") > 0))) {
            return 2147483647;
        }
        return Integer.parseInt(strNum);
    }
}
